import {
  Form,
  Button,
  DatePicker,
  Radio,
  Select,
  Steps,
  Input,
  Row,
  Col,
  InputNumber,
  Table,
  message,
} from 'antd';
import React, { Component } from 'react';
import { FormComponentProps } from 'antd/es/form';
import { TableListItem } from '../data.d';

const FormItem = Form.Item;
const { Step } = Steps;
const { TextArea } = Input;
const { Option } = Select;
const RadioGroup = Radio.Group;
import CurrencySelect from '../utils/CurrencySelect.tsx';
import Constants from '../utils/Constants';

const R = require('ramda');
import { connect } from 'dva';

export interface FormValsType extends Partial<TableListItem> {
  target?: string;
  template?: string;
  type?: string;
  time?: string;
  frequency?: string;
}

export interface UpdateFormProps extends FormComponentProps {
  handleUpdateModalVisible: (flag?: boolean, formVals?: FormValsType) => void;
  handleModalVisible: (values: FormValsType) => void;
  updateModalVisible: boolean;
  values: Partial<TableListItem>;
}

export interface UpdateFormState {
  formVals: FormValsType;
}

const orderForm = Form.create()(
  class OrderForm extends React.Component {
    static defaultProps = {
      handleModalVisible: () => {},
      handleUpdateModalVisible: () => {},
      values: {},
    };

    constructor(props: UpdateFormProps) {
      super(props);
      this.state = {
        productflag: false, //产品列表数据
        showFreight: false,
        showPremium: false,
        productList: [],
      };
    }

    statistics = {};
    handleResetFields = () => {
      this.props.form.resetFields();
      const { dispatch, handleModalVisible, handleSearch } = this.props;
      dispatch({
        type: 'productManagement/refreshState',
        payload: {
          productList: {},
        },
      });

      handleModalVisible(false);
      handleSearch();
    };

    handleChangePriceClause = value => {
      if (value === '1') {
        this.setState({ showPremium: true });
        this.setState({ showFreight: true });
      }
      if (value === '2') {
        this.props.form.setFieldsValue({ premium: 0, premiumcurrency: '' });
        this.setState({ showPremium: false });
        this.setState({ showFreight: true });
      }
      if (value === '4') {
        this.props.form.setFieldsValue({ freight: 0, freightcurrency: '' });
        this.setState({ showPremium: true });
        this.setState({ showFreight: false });
      }
      if (value !== '1' && value !== '2' && value !== '4') {
        //不是CIF，先清理保费
        this.props.form.setFieldsValue({ freight: 0, freightcurrency: '' });
        //不是C&F，再清理运费
        this.props.form.setFieldsValue({ premium: 0, premiumcurrency: '' });
        this.setState({ showFreight: false });
        this.setState({ showPremium: false });
      }
    };

    handleOpenAddProduct = () => {
      const { dispatch, orderProductDetails } = this.props;
      dispatch({
        type: 'productManagement/queryProductList',
        payload: {
          productPage: Constants.DEFAULT_PAGE,
        },
      });
      if (!this.state.productflag) {
        this.setState({ productList: orderProductDetails, productflag: true });
      }
      this.formRef.handleOpen();
    };

    handleChangeProductNumber = (record, value) => {
      const { orderProductDetails } = this.props;

      let productList = [];
      if (!this.state.productflag) {
        productList = orderProductDetails;
        this.setState({ productflag: true });
      } else {
        productList = R.clone(this.state.productList);
      }
      let customer = R.isNil(this.props.customer) ? {} : this.props.customer;
      let agencyfee = R.isNil(customer.agencyfee) ? 0 : customer.agencyfee / 100; //费率
      let retrodictRate = R.isNil(this.props.form.getFieldValue('retrodictrate'))
        ? 0
        : this.props.form.getFieldValue('retrodictrate');
      R.map(row => {
        if (row.id === record.id) {
          row.productnumber = value;
          row.productweight = Math.round(value * row.singleweight * 10000) / 10000;
          if (this.state.retrodictRate && retrodictRate !== agencyfee) {
            //倒推 数量联动单价
            let draweramount =
              R.isNil(row.draweramount) || R.isEmpty(row.draweramount) ? 0 : row.draweramount; //倒推开票金额默认为0
            let retrodictcost =
              R.isNil(row.retrodictcost) || R.isEmpty(row.retrodictcost) ? 0 : row.retrodictcost; //倒推费用默认为0
            let productnumber =
              R.isNil(row.productnumber) || R.isEmpty(row.productnumber) ? 1 : row.productnumber; //数量默认为1
            row.productprice = (
              ((draweramount * (1 + row.zzrate / 100 - row.taxrate / 100)) /
                (1 + row.zzrate / 100) +
                retrodictcost) /
              (retrodictRate - agencyfee) /
              productnumber
            ).toFixed(4);
          }
          row.totalprice = Math.round(row.productprice * row.productnumber * 100) / 100;
        }
      }, productList);
      this.setState({ productList: productList });
    };

    handleChangePackageNumber = (record, value) => {
      const { orderProductDetails } = this.props;

      let productList = [];
      if (!this.state.productflag) {
        productList = orderProductDetails;
        this.setState({ productflag: true });
      } else {
        productList = R.clone(this.state.productList);
      }
      R.map(row => {
        if (row.id === record.id) {
          row.packagenumber = value;
        }
      }, productList);
      this.setState({ productList: productList });
    };

    handleChangeProductPrice = (record, value) => {
      const { orderProductDetails } = this.props;

      let productList = [];
      if (!this.state.productflag) {
        productList = orderProductDetails;
        this.setState({ productflag: true });
      } else {
        productList = R.clone(this.state.productList);
      }
      R.map(row => {
        if (row.id === record.id) {
          row.productprice = value;
          row.totalprice = Math.round(value * row.productnumber * 100) / 100;
        }
      }, productList);
      this.setState({ productList: productList });
    };

    handleChangeProductWeight = (record, value) => {
      const { orderProductDetails } = this.props;

      let productList = [];
      if (!this.state.productflag) {
        productList = orderProductDetails;
        this.setState({ productflag: true });
      } else {
        productList = R.clone(this.state.productList);
      }
      R.map(row => {
        if (row.id === record.id) {
          row.productweight = value;
        }
      }, productList);
      this.setState({ productList: productList });
    };

    handleChangeGrossWeight = (record, value) => {
      const { orderProductDetails } = this.props;

      let productList = [];
      if (!this.state.productflag) {
        productList = orderProductDetails;
        this.setState({ productflag: true });
      } else {
        productList = R.clone(this.state.productList);
      }
      R.map(row => {
        if (row.id === record.id) {
          row.grossweight = value;
        }
      }, productList);
      this.setState({ productList: productList });
    };

    drawerMap = {};
    handleChangeDrawer = (record, value) => {
      const { orderProductDetails } = this.props;

      let productList = [];
      if (!this.state.productflag) {
        productList = orderProductDetails;
        this.setState({ productflag: true });
      } else {
        productList = R.clone(this.state.productList);
      }
      R.map(row => {
        if (row.id === record.id) {
          row.drawerid = value;
          row.drawername = this.drawerMap[value];
        }
      }, productList);
      this.setState({ productList: productList });
    };

    handleChangeProductSize = (record, e) => {
      const { orderProductDetails } = this.props;

      let productList = [];
      if (!this.state.productflag) {
        productList = orderProductDetails;
        this.setState({ productflag: true });
      } else {
        productList = R.clone(this.state.productList);
      }
      R.map(row => {
        if (row.id === record.id) {
          row.productsize = e.target.value;
        }
      }, productList);
      this.setState({ productList: productList });
    };

    handleDeleteProduct = record => {
      const { orderProductDetails } = this.props;

      let productList = [];
      if (!this.state.productflag) {
        productList = R.difference(orderProductDetails, [record]);
        this.setState({ productflag: true });
      } else {
        productList = R.difference(this.state.productList, [record]);
      }
      this.setState({ productList: productList, retrodictFlag: true });
    };

    getForm = () => {
      const { form, dispatch, recordFormValues } = this.props;
      form.validateFields((err, fieldsValue) => {
        if (err) return;
        let flag = true;

        if (flag) {
          let dataSource = { ...fieldsValue, ...this.statistics };
          dataSource.declarationstyle = '2';
          let fun = '';
          if (recordFormValues.id) {
            fun = 'productManagement/updateProduct';
            dataSource.id = recordFormValues.id;
          } else {
            fun = 'productManagement/createProduct';
          }

          dispatch({
            type: fun,
            payload: {
              dataSource: dataSource,
              onSuccess: () => {
                this.handleResetFields();
              },
              onFail: () => {
                this.handleResetFields();
              },
            },
          });
        }
      });
    };

    handleAddProducts = tempProductList => {
      this.setState({ productList: R.concat(this.state.productList, tempProductList) });
    };

    render() {
      const {
        form: { getFieldDecorator, getFieldValue },
        productList,
        list,
        recordFormValues,
      } = this.props;

      const formItemLayout = {
        labelCol: {
          xs: { span: 24 },
          sm: { span: 7 },
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 12 },
          md: { span: 10 },
        },
      };
      return (
        <div>
          <Form style={{ marginTop: 8 }}>
            <Row gutter={24}>
              <Col xs={24} md={6}>
                <FormItem label={<span>品名</span>}>
                  {getFieldDecorator('name', {
                    rules: [{ required: true, message: '请输入品名' }],
                    initialValue: productList.name,
                  })(<Input placeholder="请填写品名" />)}
                </FormItem>
              </Col>

              <Col xs={24} md={6}>
                <FormItem label={<span>型号</span>}>
                  {getFieldDecorator('model', {
                    rules: [{ required: true, message: '请输入型号' }],
                    initialValue: productList.model,
                  })(<Input placeholder="请填写型号" />)}
                </FormItem>
              </Col>
              <Col xs={24} md={6}>
                <FormItem label={<span>品牌类型</span>}>
                  {getFieldDecorator('branchtype', {
                    rules: [{ required: true, message: '品牌类型' }],
                    initialValue: productList.branchtype,
                  })(
                    <Select style={{ width: '100%' }}>
                      <option value="1" key="1">
                        无品牌
                      </option>
                      <option value="2" key="2">
                        境内自主品牌
                      </option>
                      <option value="3" key="3">
                        境外收购品牌
                      </option>
                      <option value="4" key="4">
                        境外品牌(贴牌生产)
                      </option>
                      <option value="5" key="5">
                        境外品牌(其他)
                      </option>
                    </Select>,
                  )}
                </FormItem>
              </Col>
              <Col xs={24} md={6}>
                <FormItem label={<span>品牌</span>}>
                  {getFieldDecorator('branch', {
                    rules: [{ required: true, message: '请输入品牌' }],
                    initialValue: productList.branch,
                  })(<Input placeholder="请填写品牌" />)}
                </FormItem>
              </Col>
            </Row>
            <Row gutter={24}>
              <Col xs={24} md={6}>
                <FormItem label={<span>单位</span>}>
                  {getFieldDecorator('unit', {
                    rules: [{ required: true, message: '请输入单位' }],
                    initialValue: productList.unit,
                  })(<Input placeholder="请填写单位" />)}
                </FormItem>
              </Col>
              <Col xs={24} md={6}>
                <FormItem label={<span>单价</span>}>
                  {getFieldDecorator('price', {
                    rules: [{ required: true, message: '请输入单价' }],
                    initialValue: productList.price,
                  })(<InputNumber placeholder="请填写单价" style={{ width: '100%' }} />)}
                </FormItem>
              </Col>
              <Col xs={24} md={6}>
                <FormItem label={<span>币种</span>}>
                  {getFieldDecorator('currency', {
                    rules: [{ required: true, message: '请选择币种！' }],
                    initialValue: productList.currency,
                  })(<CurrencySelect />)}
                </FormItem>
              </Col>
              <Col xs={24} md={6}>
                <FormItem label={<span>净重(kg)</span>}>
                  {getFieldDecorator('weight', {
                    rules: [{ required: true, message: '请输入净重(kg)' }],
                    initialValue: productList.weight,
                  })(<InputNumber placeholder="请填写净重(kg)" style={{ width: '100%' }} />)}
                </FormItem>
              </Col>
            </Row>
            <Row gutter={24}>
              <Col xs={24} md={6}>
                <FormItem label={<span>HSCode</span>}>
                  {getFieldDecorator('hscode', {
                    rules: [{ required: true, message: '请输入正确的税局HSCode' }],
                    initialValue: productList.hscode,
                  })(
                    <Input placeholder="请填写正确的税局HSCode" style={{ width: '100%' }} />,
                  )}
                </FormItem>
              </Col>
              <Col xs={24} md={6}>
                <FormItem label={<span>申报要素</span>}>
                  {getFieldDecorator('declarelements', {
                    rules: [{ required: true, message: '请输入申报要素' }],
                    initialValue: productList.declarelements,
                  })(<Input placeholder="请输入申报要素" />)}
                </FormItem>
              </Col>
              <Col xs={24} md={6}>
                <FormItem label={<span>规格</span>}>
                  {getFieldDecorator('size', {
                    rules: [{ required: true, message: '请输入规格' }],
                    initialValue: productList.size,
                  })(<Input placeholder="请填写规格" />)}
                </FormItem>
              </Col>
              <Col xs={24} md={6}>
                <FormItem label={<span>英文品名</span>}>
                  {getFieldDecorator('nameEn', {
                    initialValue: productList.nameEn,
                  })(<Input placeholder="请填写英文品名" />)}
                </FormItem>
              </Col>
            </Row>
            <Row gutter={24}>
              <Col xs={24} md={6}>
                <FormItem label={<span>备注</span>}>
                  {getFieldDecorator('memo', {
                    initialValue: productList.memo,
                  })(<Input placeholder="请填写备注" />)}
                </FormItem>
              </Col>
              <Col xs={24} md={6}>
                <FormItem label={<span>规格影响编码</span>}>
                  {getFieldDecorator('iseffecthscode', {
                    rules: [{ required: false, message: '请选择！' }],
                    initialValue: productList.iseffecthscode,
                  })(
                    <RadioGroup>
                      <Radio value="yes">是</Radio>
                      <Radio value="no">否</Radio>
                    </RadioGroup>,
                  )}
                </FormItem>
              </Col>
            </Row>
            <Row gutter={24}>
              <Row style={{ margin: '0 auto' }}>
                <FormItem style={{ display: 'flex', justifyContent: 'center' }}>
                  {/*<> 不会增多余节点*/}
                  <Button
                    key="forward"
                    type="primary"
                    loading={this.props.loading}
                    onClick={() => this.getForm()}
                  >
                    保存产品
                  </Button>
                  <Button
                    key="cancel"
                    style={{ marginTop: 8, marginLeft: 8 }}
                    onClick={() => this.handleResetFields()}
                  >
                    取消
                  </Button>
                </FormItem>
              </Row>
            </Row>
          </Form>
        </div>
      );
    }
  },
);

function mapStateToProps(state) {
  return {
    loading: state.loading.models.productManagement,
  };
}

export default connect(mapStateToProps)(orderForm);
